package Lono::Action::SaveToSocialtext;

use strict;
use warnings;

use Apache::Constants qw( :common );
use Apache::Request;
use Data::Dumper;
use URI::Escape;

use Lono::Recipe::Builder::Form;
use Lono::Recipe::Writer::Socialtext;

use constant WIKI_PREFIX => 'TEST ';

sub handler {
    my $r = Apache::Request->new( shift );
    my $fl = Lono::Recipe::Builder::Form->new;
    my $recipe = $fl->load( _table_to_hashref( $r->parms ) );

    my $config = _get_config( $r );
    
    $r->send_http_header( 'text/html' );

    my $sender = Lono::Recipe::Writer::Socialtext->new( $config );
    my $success = $sender->send( $recipe );
    if ( $success ) {
        my $url = _get_wiki_url( $config ) . uri_escape( WIKI_PREFIX . $recipe->get_name );
        $r->print( qq[<a href="$url">See the recipe</a>] );

    } else {
        $r->print( "An error occured. Please try again." );
    }

    return OK;
}

sub _table_to_hashref {
   my $table = shift;
   my %recipe_fields = map { $_, $table->{$_} } 
                       grep /^recipe\./, keys( %{$table} );

   return \%recipe_fields;
}

sub _get_config {
    my $r = shift;
    return {'username'  => $r->dir_config( "ST_USERNAME" ),
            'password'  => $r->dir_config( "ST_PASSWORD" ),
            'server'    => $r->dir_config( "ST_SERVER" ),
            'workspace' => $r->dir_config( "ST_WORKSPACE" )};
}

sub _get_wiki_url {
    my $config = shift;
    return $config->{'server'} . '/' . $config->{'workspace'} . '/index.cgi?';
}

1;
